#!/bin/bash -e
#
#   Neutron3529's Unity Game Plugin
#   Copyright (C) 2022 Neutron3529
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as
#   published by the Free Software Foundation, either version 3 of the
#   License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
############################################################################
#
#   * compile instructions: put this file and `utils.cs` in `steamapps`
#   * folder, open a terminal in the same folder, and execute:
#   *
#   * ```
#   *     chmod +x ${file}.cs
#   *     ./${file}.cs
#   * ```
#   *
#   * then the mod will be compiled automatically.
#   *
#   * Here we wrote a shebang like file, which is correct
#   * in my computer (Manjaro XFCE), if such script do not work
#   * in your computer, you could just try the instructions below :

export GAME_NAME="${0%\.cs}"                                # might modify if the name mismatch.
export GAME_DIR="Kingdoms and Castles"                                # might be modified, but "$GAME_NAME" cover most of the cases.

export FILE_NAME="$0"
export ASSEMBLY="Assembly-CSharp"                           # might be modified
export UTILS="utils.cs"                                     # might be modified if you do not put utils.cs in the current dir.
export PLUGIN_ID="Neutron3529.Cheat"                        # should be modified
export NAMESPACE_ID="Neutron3529.Cheat"                     # should be modified
export GAME_BASE_DIR="common/$GAME_DIR"                     # should modify GAME_DIR instead since GAME_DIR == GAME_NAME is almost always true.

export IFS=$'\n' # to disable the annoying space.
export DOTNET="dotnet" # the location of the DOTNET executable file.
[ -z "$DOTNET_CSC_DLL" ] && export DOTNET_CSC_DLL=`\ls /usr/share/dotnet/sdk/*/Roslyn/bincore/csc.dll` # In manjaro, the csc.dll is located in /usr/share/dotnet/sdk/*/Roslyn/bincore/csc.dll

case $1 in
  V)       EXTRA_DEFINE="-define:DEBUG${IFS}-define:VERBOSE${IFS}-debug" ;;
  v)       EXTRA_DEFINE="-define:DEBUG${IFS}-define:VERBOSE${IFS}-debug" ;;
  VERBOSE) EXTRA_DEFINE="-define:DEBUG${IFS}-define:VERBOSE${IFS}-debug" ;;
  verbose) EXTRA_DEFINE="-define:DEBUG${IFS}-define:VERBOSE${IFS}-debug" ;;
  D)       EXTRA_DEFINE="-define:DEBUG${IFS}-debug"                      ;;
  d)       EXTRA_DEFINE="-define:DEBUG${IFS}-debug"                      ;;
  DEBUG)   EXTRA_DEFINE="-define:DEBUG${IFS}-debug"                      ;;
  debug)   EXTRA_DEFINE="-define:DEBUG${IFS}-debug"                      ;;
  *)       EXTRA_DEFINE=""                                               ;;
esac

_MODE__SELECT_=100

( yes "" | head -n $_MODE__SELECT_ | head -n-1  ; tail $FILE_NAME -n+$_MODE__SELECT_) | sed s/%%NAMESPACE_ID%%/${NAMESPACE_ID}/g | sed s/%%PLUGIN_ID%%/${PLUGIN_ID}/g | $DOTNET $DOTNET_CSC_DLL -nologo -t:library \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/0Harmony.dll" \
  -r:"${GAME_BASE_DIR}/BepInEx/core/BepInEx.Harmony.dll" \
  `[ -e "${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll" ] && echo "-r:\"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/netstandard.dll\""` \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/System.Core.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.AIModule.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.CoreModule.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/UnityEngine.UI.dll" \
  -r:"${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/mscorlib.dll" \
  $(for i in "${GAME_BASE_DIR}/${GAME_NAME}_Data/Managed/$ASSEMBLY"*.dll ; do echo -e "-r:\"$i\"\n" ; done) \
  -out:"${GAME_BASE_DIR}/BepInEx/plugins/${FILE_NAME%.*}".dll \
  -optimize $EXTRA_DEFINE \
  - $UTILS && rm -f "${GAME_BASE_DIR}/BepInEx/config/${PLUGIN_ID}.cfg";

if [ -n "$2" ]; then
  git add ${FILE_NAME}
  case $2 in
    R) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    r) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    RANDOM) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    random) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    U) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    u) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    UPLOAD) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    upload) git commit -am "`curl -s https://whatthecommit.com/index.txt`" ;;
    *) git commit -am "$2" ;;
  esac
  git push
fi
exit





using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;

using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;

namespace %%NAMESPACE_ID%%;

[BepInPlugin("%%PLUGIN_ID%%", "%%NAMESPACE_ID%%", "0.1.0")]
public class Cheat : Neutron3529.ModEntry {
    public Cheat() : base("%%PLUGIN_ID%%") {}
    public override void Awake() {
        base.Awake();
        // 主要逻辑放在`utils.cs`中，这里的Awake2只是为了以防万一
        // 目前来说，这个函数的唯一用途是用来“叮”……
        // 就像这样：
        logger("叮~修改器启动，请安心游戏");
    }
    class mill : Entry {
        [Desc("与风车距离小于此数值的土地自动肥沃")]
        static int val=3;
        [HarmonyPatch(typeof(Windmill),"OnBuilt")]
        public static void Prefix(Building ___b){
            if(___b.IsPlayerBuilding()){
                for(int i=___b.GetCell().x-val;i<=___b.GetCell().x+val;i++){
                    for(int j=___b.GetCell().z-val;j<=___b.GetCell().z+val;j++){
                        var cell=World.inst.GetCellData(i,j);
                        if(cell!=null && World.GetLandmassOwner(cell.landMassIdx)==Player.inst.PlayerLandmassOwner){
                            TerrainGen.inst.SetFertileTile(cell.x,cell.z,2);
                        }
                    }
                }
            }
        }
    }
    class wood : Entry {
        [Desc("玩家地格树木产出倍率",1)]
        static int mul=10;
        [HarmonyPatch(typeof(Assets.Code.Jobs.BaseCutterJob),"DoHarvest")]
        public static void Postfix(ref int __result, Cell ___cellToChop){
            if(World.GetLandmassOwner(___cellToChop.landMassIdx)==Player.inst.PlayerLandmassOwner){
                __result*=mul;
            }
        }
    }
    class producer : Entry {
        [Desc("玩家建筑产出倍率",1)]
        static int mul=10;
        [HarmonyPatch(typeof(ProducerBase),"OnYieldResources")]
        public static void Prefix(ref Assets.Code.ResourceAmount Yield, Building ___b){
            if(___b.IsPlayerBuilding()){
                Yield*=mul;
            }
        }
    }
    [Desc("玩家资源无限")]
    class infinite : Entry {
        [HarmonyPatch(typeof(ResourceTracker),"AddHarvested")]
        static bool Prefix(ResourceTracker __instance, ref bool __result){
            if(World.GetLandmassOwner(World.inst.GetCellData(__instance.Pos).landMassIdx)==Player.inst.PlayerLandmassOwner){
                return __result=false;
            }
            return true;
        }
        // [Desc("玩家铁矿无限")]
        // static bool iron=true;
        // [Desc("玩家大铁矿无限")]
        // static bool ironL=true;
        // [Desc("玩家石矿无限")]
        // static bool quarry=true;
        // [Desc("玩家大石矿无限")]
        // static bool quarryL=true;
        // static IEnumerable<MethodBase> TargetMethods() {// used for several Distance methods.
        //     if(iron)yield return typeof(IronMine).GetMethod("ConsumePrereqs");
        //     if(ironL)yield return typeof(LargeIronMine).GetMethod("ConsumePrereqs");
        //     if(quarry)yield return typeof(Quarry).GetMethod("ConsumePrereqs");
        //     if(quarryL)yield return typeof(LargeQuarry).GetMethod("ConsumePrereqs");
        // }
        // static bool Prefix(ref bool __result){
        //     __result=true;
        //     return false;
        // }

    }
    class tax : Entry {
        [Desc("玩家税收产能",1)]
        static int mul=10;
        [HarmonyPatch(typeof(Home),"Start")]
        public static void Prefix(ref float ___taxYield, Building ___b){
            if(___b.IsPlayerBuilding()){
                ___taxYield*=mul;
            }
        }
    }
    class yielder : Entry {
        [Desc("玩家建筑生产速率",1)]
        static int mul=10;
        [HarmonyPatch(typeof(YieldProducer),"UpdateYield")]
        public static void Prefix(ref float dt, Building ___b){
            if(___b.IsPlayerBuilding()){
                dt*=mul;
            }
        }
    }
    [Desc("弩炮无敌化")]
    class ballista : Entry {
        [HarmonyPatch(typeof(ProjectileDefense),"Start")]
        public static void Prefix(ref int ___frameSpread, Building ___b, ref float ___insideRangeIncreasePerHeight, ref float ___AttackTime){
            if(___b.IsPlayerBuilding()){
                ___frameSpread=4;
                ___insideRangeIncreasePerHeight=0f;
                ___AttackTime=0.25f;
            }
        }
    }
    class carry : Entry {
        [Desc("全部村民携带能力倍率",1)]
        static int cmul=10;
        [Desc("全部村民移动速度倍率",1)]
        static float mmul=10;
        [HarmonyPatch(typeof(Villager),"TryEat")]
        public static void Postfix(Villager __instance){
            if(World.GetLandmassOwner(World.inst.GetCellData(__instance.Pos).landMassIdx)==Player.inst.PlayerLandmassOwner){
                if(cmul>1)__instance.bonusMultiplier=cmul;
                if(mmul>1)__instance.speedBonusMultiplier=mmul;
            }
        }
    }
    [Desc("初始资源全满")]
    class keep : Entry {
        [HarmonyPatch(typeof(Keep),"OnInit")]
        public static void Postfix(Keep __instance, Building ___b){
            if(___b.IsPlayerBuilding()){
                __instance.woodStack.Clear();
                __instance.woodStack.Add(__instance.woodStack.MaxCapacity());
                __instance.stoneStack.Clear();
                __instance.stoneStack.Add(__instance.stoneStack.MaxCapacity());
                __instance.foodStack.Clear();
                __instance.foodStack.Add(__instance.foodStack.MaxCapacity());
                __instance.appleStack.Clear();
                __instance.appleStack.Add(__instance.appleStack.MaxCapacity());
            }
        }
    }
    class keep_range : Entry {
        [Desc("老家弓箭射程修改",1)]
        static float val=30;
        [HarmonyPatch(typeof(Keep),"FullRange")]
        public static bool Prefix(ref float __result, Building ___b){
            if(___b.IsPlayerBuilding()){
                __result=val;
                return false;
            } else {
                return true;
            }
        }
    }
    class archer : Entry {
        [Desc("弓箭手永远最大射程")]
        static bool maxrange=true;
        [Desc("最大射程额外加值",0)]
        static float range_add=10;
        [HarmonyPatch(typeof(ArcherGeneral),"Start")]
        public static void Prefix(ref float ___rangeIncreasePerHeight, ref float ___attackRange, int ___maxHeight, UnitSystem.Army ___army){
            if(___army.teamId==Player.inst.PlayerLandmassOwner.teamId){
                if(maxrange){
                    ___attackRange+=___rangeIncreasePerHeight*___maxHeight;
                    ___rangeIncreasePerHeight=0f;
                }
                if(range_add>0){
                    ___attackRange+=range_add;
                }
            }
        }
    }
}
